<!-- 不带弹框国标对讲 -->
<template>
  <div>
    <audio id="noDialogTalkPlayer" ref="noDialogTalkPlayer" autoplay v-show="1===0" muted> </audio>
<!--    <canvas id="noDialogTalkCanvas" ref="noDialogTalkCanvas" style="width: 100%;height: 100%" ></canvas>-->
  </div>
</template>
<script>
import Device from "@/api/Device";
import MediaDevice from "@/api/MediaDevice";
import {apiResult} from "@/libs/util";

export default {
  name:"GbTalkUnDialogPlayer",
  data(){
    return{
      api: new Device(),
      push:{
        url: null,
        deviceId: null,
        stream: null,
        app: "live",
        host: null
      },
      animation:{
        timers:null,
        mediaStream:null,
        audioCtx:null,
        waveTimer:null,
      },
      callBack:null,
      //talkElement: null,
      talkPlayer:null,
      audioCanvas:null,
      MediaStreamTrack:null,
      result:{
        code: 1, //0正对讲  0 关闭对讲， -1 异常错误
        msg:null,
      }
    }
  },
  methods:{
    openDialog(deviceId,channelId,audioCanvas,callBack) {
      this.callBack = callBack;
      this.audioCanvas = audioCanvas;
      const _this = this;
      const constraints = { audio: true};
      navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) {
        //关闭 MIC使用
        _this.MediaStreamTrack=typeof mediaStream.stop==='function'?mediaStream:mediaStream.getTracks()[0];
        _this.animation.mediaStream = mediaStream;
        _this.init(deviceId,channelId);
      }).catch((err)=>{
        //this.$Message.error();
        if (!!callBack){
          this.stop();
          this.genCallBack({code:-1,msg:this.$t('device_init_failed')})
          //callBack({code:-1,msg:this.$t('device_init_failed')});
        }
      })
    },

    init(deviceId,channelId){
      this.push.deviceId = deviceId;
      this.push.stream = deviceId + "_" + channelId + "_gbtalk";
      let pushUrl = "http://192.168.0.129:8080/index/api/webrtc?app=live&stream=" + this.push.stream + "&type=push";
      this.push.url = this.api.getPushUrl(pushUrl);
      //console.log(">>>>> push=%o",this.push);
      this.api.playGbTalk(deviceId,this.push.app,this.push.stream).then((res)=>{
          apiResult(res.data,false,result=>{
            //广播发出成功，可以推流了
            this.startPushStream();
          },err=>{
            // 广播失败，关闭窗口
            this.stop();
            this.genCallBack({code:-1,msg:this.$t('talk_brocast_failed')})
          })
        /*if (res.data.code === 0){
          //广播发出成功，可以推流了
          this.startPushStream();
        }else{
          console.log(res.data.msg);
          // 广播失败，关闭窗口
          this.stop();
          this.genCallBack({code:-1,msg:this.$t('talk_brocast_failed')})
          //this.callBack({code:-1,msg:this.$t('talk_brocast_failed')});
        }*/
      })
    },

    /**
     * 开始推流
     */
    startPushStream(){
      const _this = this;
      this.talkPlayer = new ZLMRTCClient.Endpoint({
        element: _this.$refs.noDialogTalkPlayer,// video 标签
        debug: true,// 是否打印日志
        zlmsdpUrl: _this.push.url,//流地址
        simulecast: false,
        useCamera: false,
        audioEnable: true,
        videoEnable: false,
        recvOnly: false,
      })
      //协商出错
      this.talkPlayer.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR,(e)=>{// ICE 协商出错
        console.error('ICE 协商出错: %o',e);

        //_this.callBack({code:-1,msg:this.$t('talk_ice_failed')});
        _this.genCallBack({code:-1,msg:this.$t('talk_ice_failed')})
        //_this.returnCallBack({code:-1,msg:"推语音流出错"})
      });
      this.talkPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE,function(state) {// RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
        console.log('当前状态==>', state)
        if ("connected" === state){
          //_this.returnCallBack({code:0,msg:"开始对讲"})
          _this.genCallBack({code:1,msg:_this.$t('start_the_intercom')})
          _this.genAudioWave();
        }
      });
    },
    /**
     * 音频波形图
     */
    genAudioWave(){
      const _this = this;
      if (!!this.animation.mediaStream){
        new MediaDevice().audioWave(_this.animation.mediaStream,_this.audioCanvas,
          (res)=>{
            //console.log(">>>> audioWave: res=%o",res);
            _this.animation.audioCtx = res.audioCtx;
            _this.animation.waveTimer = res.timer;
          })
      }
    },

    stop(){
      if(this.talkPlayer){
        this.talkPlayer.close();
        this.talkPlayer = null;

        this.$refs.noDialogTalkPlayer.srcObject = null;
        this.$refs.noDialogTalkPlayer.load();
      }

      this.MediaStreamTrack && this.MediaStreamTrack.stop();
      this.animation.mediaStream = null;
      if (!!this.animation.audioCtx){
        this.animation.audioCtx.close();
        this.animation.audioCtx=null;
      }

      if (!!this.animation.waveTimer){
        clearInterval(this.animation.waveTimer)
        this.animation.waveTimer=null;
      }
    },

    close(){
      this.stop();
      //this.genCallBack({code:0,msg:this.$t('end_the_intercom')})
    },

    genCallBack(result){
      if (!!this.callBack)
        this.callBack(result);
    }
  }

}

</script>
<style lang="less">

</style>
